﻿
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;

}
var ChatYahoo = false;
var ChangeAvatar = false;
var idcurrent = -1;
var Myaccount = null;
var ConnectedYahoo = false;


var demo = null;
var liststatus = [];
liststatus[0] = "online";
liststatus[1] = "busy";
liststatus[2] = "idle";
liststatus[3] = "offline";
var currentparent;

var listTab = [];
var model = [];
var netWork = [];
netWork["yahoo"] = 1;
netWork["webchat"] = 0;
var LengthModels = [];
LengthModels["yahoo"] = 0;
LengthModels["webchat"] = 0;
var seq = 0;
var totalFriendYahoo = 0;
function buildModel(data) {
    model[netWork["webchat"]] = [];
    $.each(data, function (i, item) {
        model[netWork["webchat"]][i] = item;
    });

}
function splitID(id) {

    var n = id.split("_");
    var netword = parseInt(n[0]);
    var index = parseInt(n[1]);
    return [netword, index];
}
function SubID(id, ex) {
    var leng = ex.length;
    return id.substr(leng, id.length);
}
function findIDFromModel(network, id) {
    for (var i = 0; i < LengthModels[network]; i++) {
        if (model[netWork[network]][i]["ID"] == id) {
            return i;

        }
    }
    return -1;
}
function cutStringLong(str, lenMax) {
    var st = "";

    var result = str;
    if (str.length > lenMax)
        result = str.substr(0, lenMax) + " ...";
    return result;
}
function loadimage(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

        // Only process image files.
        if (!f.type.match('image.*')) {
            continue;
        }

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                // Render thumbnail.
                var span = document.getElementById('currentavatar');

                span.src = e.target.result;
                $("#currentavatar").hide();
                $("#currentavatar").fadeIn(1500);
                ChangeAvatar = true;
            };
        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    }
}
function buildModelYahoo(data) {
    model[netWork["yahoo"]] = [];
    var Contacts = data["contacts"];
    totalFriendYahoo = data["total"];
    for (var i = 0 ; i < totalFriendYahoo; i++) {

        var contact = Contacts[i]["contact"];
        model[netWork["yahoo"]][i] = [];
        model[netWork["yahoo"]][i]["ID"] = contact["id"];
        model[netWork["yahoo"]][i]["FullName"] = cutStringLong(contact["id"], 20);
        var status = contact["presence"]["presenceState"];
        var AoStatus = 0;
        switch (status) {
            case 0:
                AoStatus = 0;
                break;
            case 2:
                AoStatus = 1;
                break;
            case 999:
                AoStatus = 2;
                break;
            case -1:
                AoStatus = 3;
        }

        model[netWork["yahoo"]][i]["status"] = AoStatus;
    };
    LengthModels["yahoo"] = totalFriendYahoo;
}
function changeCurrentChat(value) {
    currentChat = value;
    var newid = splitID(currentChat);
    document.getElementById('friendavatar').src = "http://localhost:40000/api/account/" + model[newid[0]][newid[1]]["ID"] + "/avatar";
}
function AddModel(data) {

    model[netWork["webchat"]][LengthModels["webchat"]] = data;


}
function ShowFormChangeAvatar() {

    document.getElementById('currentavatar').src = "http://localhost:40000/api/account/" + Myaccount.ID + "/avatar";
    DialogChangeAvatar.show();
    ChangeAvatar = false;

}
var currentChat = null;
var numberTab = 0;
var InfoLoginYahoo = null;
function logout() {

    $.ajax({

        url: "http://localhost:40000/api/login/" + idcurrent,


        type: "POST",

        statusCode: {

            200: function (data) {
                setCookie("login", "", -2);
                window.location = "/";
            },
            //Unauthorized
            401: function () {

                setCookie("login", "", -2);
                alert('bạn chưa đăng nhập!');
                window.location = "/";
            }
        }


    });

}
function RemoveFriend(node) {
    var fid = SubID(node.id, "friend");
    var newId = splitID(fid);
    $.ajax({


        url: "http://localhost:40000/api/friend?mid=" + idcurrent + "&fid=" + model[netWork["webchat"]][newId[1]]["ID"],
        type: "POST",

        statusCode: {

            200: function (data) {
                if (data == true)
                    currentparent.removeChild(node);
            },
            //Unauthorized
            401: function () {

                setCookie("login", "", -2);
                alert('bạn chưa đăng nhập!');
                window.location = "/";
            }
        }

    });
    myDialog.onCancel();
};




require(["dojo/ready", "dojo/parser", "dijit/registry", "dijit/layout/BorderContainer",
"dijit/layout/TabContainer", "dijit/layout/ContentPane",
"dijit/form/Textarea", "dijit/form/Button",
"dijit/MenuBar", "dijit/PopupMenuBarItem", "dijit/Menu", "dijit/MenuItem", "dijit/DropDownMenu",
"dijit/Dialog", "dijit/PopupMenuItem",

                       "dojo/query",
                       "dojo/mouse",
                       "dojo/on",
                       "dojo/dom-class",
                       "dojo/_base/lang",
                        "dojo/dom",
                        "dojo/keys"

],

function (ready, parser, registry, BorderContainer, TabContainer, ContentPane, Textarea,
    Button, MenuBar, PopupMenuBarItem, Menu, MenuItem, DropDownMenu, Dialog, PopupMenuItem,
    query, mouse, on, domClass, lang, dom, keys

    ) {
    function AddTab(id, selected) {
        var newid = splitID(id);

        var pane = new ContentPane({
            title: model[newid[0]][newid[1]]["FullName"],
            closable: true,
            id: "panel" + id,
            onClose: function () {
                // confirm() returns true or false, so return that.

                var r = confirm("Do you really want to Close this?");
                if (r == true) {
                    listTab[id] = false;
                    changeNumerTab(-1);
                }
                return r;
            }
        });
        var paneltab = registry.byId("tabPanel");
        paneltab.addChild(pane);

        changeNumerTab(1);
        if (selected == true)
            registry.byId("tabPanel").selectChild(pane);
        return pane;

    }
    function setSelectedPanelYahoo() {
        var panelyahoo = registry.byId("leftColYahoo");


        registry.byId("PanelLeft").selectChild(panelyahoo);
        ChatYahoo = true;
    }
    function changeNumerTab(value) {
        numberTab += value;

        var textSend = registry.byId("textSend");
        var textSendno2 = dom.byId("textSend");
        if (numberTab > 0) {

            textSend.disabled = false;
            textSendno2.disabled = false;
            textSend.focus();
            $("#friendavatar").show(500);
            $("#connect").slideDown(3000);
        } else {
            textSendno2.disabled = true;
            currentChat = null;
            $("#friendavatar").hide();
            $("#connect").hide();
        }
    }
    function getAllContact() {
        var link = "/api/yahoo?action=contact" +
            "&sid=" + InfoLoginYahoo["sessionId"] +
            "&oauth_token=" + InfoLoginYahoo["oauth_token"] +
            "&oauth_token_secret=" + InfoLoginYahoo["oauth_token_secret"] +
            "&seq=" + seq;
        $.ajax({
            url: link,
            dataType: 'json',
            contentType: 'application/json',
            type: "GET",


            success: function (data) {
                buildModelYahoo(data);
                setSelectedPanelYahoo();
                for (var i = 0 ; i < totalFriendYahoo; i++) {

                    Myaccount.UserNameYahoo = $("#nicknameYahoo").val();
                    var temp = model[netWork["yahoo"]][i];
                    addDivAccountYahoo(netWork["yahoo"] + "_" + i, temp["FullName"], temp["status"]);
                    ConnectedYahoo = true;

                };


                refresh();

            },
            complete: function (XMLHttpRequest, textStatus) {

                $('#loading').hide();
            },
            error: function (errMsg) {
                InfoLoginYahoo = null;
                alert("Kết nối yahoo bị lỗi!");
            }
        });
    }
    function rememberConnectToYahoo(username, password) {
        var link = "http://localhost:40000/api/account?action=rememberpasswordyahoo&mid=" + Myaccount.ID + "&yusername=" + username + "&ypassword=" + password;
        $.ajax({
            url: link,
            dataType: 'json',
            contentType: 'application/json',
            type: "POST",


            success: function (data) {
                if (data == true) {
                    getAllContact();
                }
                else {
                    $('#loading').hide();
                    alert("Kết nối tới yahoo thất bại!");
                    InfoLoginYahoo = null;
                }
            },
            error: function (errMsg) {

                alert("Kết nối yahoo bị lỗi!");
                $('#loading').hide();
                InfoLoginYahoo = null;
            }
        });
    }
    function ConnectToYahooWhenLogin(username, password) {
        if (ConnectedYahoo == false && username != null) {

            $('#loading').show();
            var link = "/api/yahoo?username=" + username + "&password=" + password;
            $.ajax({
                url: link,
                dataType: 'json',
                contentType: 'application/json',
                type: "GET",


                success: function (data) {

                    InfoLoginYahoo = data;

                    getAllContact();


                },
                error: function (errMsg) {
                    $('#loading').hide();
                    alert("Kết nối yahoo bị lỗi!");
                }
            });
            DialogConnectYahoo.onCancel();
        }


    }
    function GetYourInfo() {
        var username = getCookie("login");
        if (username != null) {
            idcurrent = parseInt(username);

            $.ajax({
                url: "http://localhost:40000/api/account/" + idcurrent,

                type: "GET",

                dataType: 'json',
                statusCode: {
                    //OK
                    200: function (result) {

                        Myaccount = result;
                        document.getElementById('myname').innerHTML = Myaccount.FullName;
                        document.getElementById('myavatar').src = "http://localhost:40000/api/account/" + Myaccount.ID + "/avatar"
                        ConnectToYahooWhenLogin(Myaccount.UserNameYahoo, Myaccount.PassWordYahoo);
                    },
                    //Unauthorized
                    401: function () {
                        setCookie("login", "", -2);
                        window.location = "/";

                    }
                }


            });
        }
        else
            window.location = "/";
    }
    function refresh() {
        if (demo != null) {

            demo.taskNodes = query(".account");
            demo.taskNodes.on("click", function (evt) {
                demo.updateCurrentTask(evt.target);

            });
            demo.taskNodes.on(mouse.enter, function (evt) {
                demo.updateHoveredTask(evt.target);
            });

        }
    }
    function addDivAccount(id, fullname, status) {
        var newid = splitID(id);

        var divaccount = " <div class=\"account\" id=\"friend" + id + "\" ><img  alt=\"not avatar\" src=\"http://localhost:40000/api/account/" + model[newid[0]][newid[1]]["ID"] + "/avatar\" style =\"width:40px;height:40px;float:left;\"/><img   src=\"/Images/" + liststatus[status] + ".png\" style =\"width:32px;height:32px;float:left;\"/><p>" + fullname + "</p></div>";
        $("#leftCol").append(divaccount);
        $("#friend" + id).hide();
        $("#friend" + id).fadeIn(1000);

        LengthModels["webchat"]++;

        refresh();


    }
    function addDivAccountYahoo(id, fullname, status) {
        var divaccount = " <div class=\"account\" id=\"friend" + id + "\" ><img  alt=\"not avatar\" src=\"http://localhost:40000/api/account/" + id + "/avatar\" style =\"width:40px;height:40px;float:left;\"/><img   src=\"/Images/" + liststatus[status] + ".png\" style =\"width:32px;height:32px;float:left;\"/><p>" + fullname + "</p></div>";
        $("#leftColYahoo").append(divaccount);
        $("#friendYahoo" + id).hide();
        $("#friendYahoo" + id).fadeIn(1000);




    }
    function addMessage(id, fullname, Content) {
        var divMessage = " <div class=\"sendmessage\" ><img  alt=\"not avatar\" src=\"http://localhost:40000/api/account/" + idcurrent + "/avatar\"/> <div ><p id = \"nick\"><b>" + Myaccount.FullName + "</b></p><p id= \"content\" >" + Content + "</p></div> </div>";
        $("#panel" + id).append(divMessage);
        $("#panel" + id).animate({ scrollTop: $("#panel" + id)[0].scrollHeight }, 500);


    }
    function addMessageReceive(id, Content) {


        if (listTab[id] != true) {
            listTab[id] = true;
            AddTab(id);

        }
        var newid = splitID(id);
        if (currentChat == null)
            changeCurrentChat(id);
        var divMessage = " <div class=\"sendmessage\" ><img  alt=\"not avatar\" src=\"http://localhost:40000/api/account/" + model[newid[0]][newid[1]]["ID"] + "/avatar\"/> <div ><p id = \"nick\"><b>" + model[newid[0]][newid[1]]["FullName"] + "</b></p><p id= \"contentReceive\" >" + Content + "</p></div> </div>";
        $("#panel" + id).append(divMessage);
        $("#panel" + id).animate({ scrollTop: $("#panel" + id)[0].scrollHeight }, 0);

    }
    function addFriend() {
        $.ajax({

            url: "http://localhost:40000/api/friend?mid=" + idcurrent + "&fusername=" + $("#name").val(),
            type: "GET",

            dataType: 'json',
            statusCode: {
                //OK
                200: function (data) {
                    if (data != null) {
                        AddModel(data);
                        addDivAccount(netWork["webchat"] + "_" + LengthModels["webchat"], data.FullName, data.Status);

                    }
                    else
                        alert('Không tồn tại nickname trên!')
                },
                //Unauthorized
                401: function () {
                    alert('bạn chưa đăng nhập!')
                    window.location = "/";

                }
            }

        });
        myDialog.onCancel();
    }
    function changePassWord() {
        var oldpass = $("#oldPassWord").val();
        var newpass = $("#newPassWord").val();
        var confirmPass = $("#confirmNewPassWord").val();
        if (oldpass != Myaccount.PassWord) {
            alert("Old Password incorrect!");
            return;
        }
        if (newpass == "" || newpass != confirmPass) {
            alert("confirm Password incorrect!");
            return;
        }
        $.ajax({

            url: "http://localhost:40000/api/account?action=changepassword&mid=" + Myaccount.ID + "&newpassword=" + newpass,
            type: "POST",

            dataType: 'json',
            statusCode: {
                //OK
                200: function (data) {
                    if (data == true) {
                        alert("đổi password thành công!");

                    }
                    else
                        alert('đổi password thất bại!')
                },
                //Unauthorized
                401: function () {
                    alert('bạn chưa đăng nhập!')
                    window.location = "/";

                }
            }

        });
        DialogChangePassWord.onCancel();
    }
    function SendMessageToServer(myid, contentMessage) {




        if (contentMessage == "")
            return;

        var newid = splitID(currentChat);
        var friendid = model[newid[0]][newid[1]]["ID"];
        switch (newid[0]) {
            case netWork["webchat"]:
                var Message = {
                    IDAccountSend: myid,
                    IDAccountReceive: friendid,
                    Content: contentMessage

                };
                var jsontext = JSON.stringify(Message);
                $.ajax({
                    url: "http://localhost:40000/api/message/",
                    dataType: 'json',
                    contentType: 'application/json',
                    type: "POST",
                    crossDomain: false,
                    data: jsontext,
                    success: function (data) {

                        addMessage(currentChat, Myaccount.FullName, contentMessage);
                        var textSend = dom.byId("textSend");
                        textSend.value = "";
                    },
                    error: function (errMsg) {
                        alert("Bạn chưa chọn bạn chát");
                    }
                });
                break;
            case netWork["yahoo"]:

                var link = "/api/yahoo?action=sendmessage" +
            "&sid=" + InfoLoginYahoo["sessionId"] +
            "&oauth_token=" + InfoLoginYahoo["oauth_token"] +
            "&oauth_token_secret=" + InfoLoginYahoo["oauth_token_secret"] +
                    "&fid=" + friendid;
                var messagesend = { Message: contentMessage };
                var stringsend = JSON.stringify(messagesend);
                $.ajax({
                    url: link,
                    dataType: 'json',
                    contentType: 'application/json',
                    type: "POST",
                    data: stringsend,
                    statusCode: {
                        //OK
                        200: function (data) {
                            addMessage(currentChat, Myaccount.FullName, contentMessage);
                            var textSend = dom.byId("textSend");
                            textSend.value = "";
                        },
                        //Unauthorized
                        401: function () {
                            alert('bạn chưa đăng nhập!')
                            window.location = "/";

                        }
                    }

                });
                break;

        }
    }
    function ConnectToYahoo() {
        if (ConnectedYahoo == false) {
            var username = $("#nicknameYahoo").val();
            var password = $("#passwordYahoo").val();
            $('#loading').show();
            var link = "/api/yahoo?username=" + username + "&password=" + password;
            $.ajax({
                url: link,
                dataType: 'json',
                contentType: 'application/json',
                type: "GET",


                success: function (data) {

                    InfoLoginYahoo = data;

                    rememberConnectToYahoo(username, password);


                },
                error: function (errMsg) {
                    $('#loading').hide();
                    alert("Kết nối yahoo bị lỗi!");
                }
            });
            DialogConnectYahoo.onCancel();
        }
        else
            alert("bạn đã kết nối thành công tới yahoo messger!")

    }


    function AddMenu() {

        var pMenu;

        demo = {
            taskNodes: null, // used to store task DOM nodes for reuse later



            currentTaskNode: null, // currently "selected" task



            // handler for clicks on task context menu items
            onTaskItemClick: function (evt) {

                RemoveFriend(this.currentTaskNode);
            },


            // called when one of the task nodes is clicked
            updateCurrentTask: function (node) {

                // update currentTaskNode for future use

                for (var j = 0 ; j < this.taskNodes.length ; j++) {
                    if (this.taskNodes[j] == node) {
                        this.currentTaskNode = node;

                        break;
                    }
                    else if (this.taskNodes[j] == node.parentNode) {
                        this.currentTaskNode = node.parentNode;
                        break;
                    }

                };
                if (listTab[SubID(this.currentTaskNode.id, "friend")] != true) {
                    listTab[SubID(this.currentTaskNode.id, "friend")] = true;


                    AddTab(SubID(this.currentTaskNode.id, "friend"), true);
                }
                else {

                    var h = registry.byId("panel" + SubID(this.currentTaskNode.id, "friend"));
                    registry.byId("tabPanel").selectChild(h);
                }
                changeCurrentChat(SubID(this.currentTaskNode.id, "friend"));
            },
            updateHoveredTask: function (node) {
                for (var j = 0 ; j < this.taskNodes.length ; j++) {
                    if (this.taskNodes[j] == node) {
                        this.currentTaskNode = node;

                        break;
                    }
                    else if (this.taskNodes[j] == node.parentNode) {
                        this.currentTaskNode = node.parentNode;
                        break;
                    }

                };
            }


        }

        refresh();

        // build menu
        pMenu = new Menu({
            targetNodeIds: ["leftCol"],
            selector: ".account"
        });
        pMenu.addChild(new MenuItem({
            label: "Delete Account",
            onClick: lang.hitch(demo, "onTaskItemClick")
        }));
        pMenu.addChild(new MenuItem({
            label: "Send message"

        }));


        pMenu.startup();

    }
    ready(function () {

        currentparent = dom.byId("leftCol");

        parser.parse();

        GetYourInfo();

        setInterval(function () {
            $.ajax({
                url: "http://localhost:40000/api/message/" + Myaccount.ID,
                dataType: 'json',
                success: function (data) {
                    //Update your dashboard gauge

                    $.each(data, function (i, item) {
                        var id = findIDFromModel("webchat", item.IDAccountSend);
                        if (id != -1) {
                            switch (item.Action) {
                                case "login":
                                    document.getElementById("friend" + netWork["webchat"] + "_" + id).childNodes[1].src = "./Images/online.png";
                                    break;
                                case "logout":
                                    var hehe = document.getElementById("friend" + netWork["webchat"] + "_" + id);
                                    hehe.childNodes[1].src = "./Images/offline.png";
                                    break;
                                default:
                                    var id = findIDFromModel("webchat", item.IDAccountSend);
                                    if (id != -1)
                                        addMessageReceive(netWork["webchat"] + "_" + id, item.Content);
                            }
                        }
                    });
                }
            });

            if (InfoLoginYahoo != null) {
                var link = "/api/yahoo?action=getnotifycation" +
            "&sid=" + InfoLoginYahoo["sessionId"] +
            "&oauth_token=" + InfoLoginYahoo["oauth_token"] +
            "&oauth_token_secret=" + InfoLoginYahoo["oauth_token_secret"] +
                    "&seq=" + seq;


                $.ajax({
                    url: link,
                    dataType: 'json',
                    success: function (data) {
                        if (data != null) {
                            var responses = data["responses"];

                            $.each(responses, function (i, item) {
                                if (i == 0) {
                                    seq = 0;
                                    var buddy = item["buddyInfo"];
                                    if (buddy != null)
                                        seq += buddy.sequence + responses.length;
                                    var mg = item["message"];
                                    if (mg != null)
                                        seq += mg.sequence + responses.length;
                                    var ba = item["buddyAuthorize"];
                                    if (ba != null)
                                        seq += ba.sequence + responses.length;

                                }
                                var message = item["message"];

                                if (message != null) {
                                    var fid = findIDFromModel("yahoo", message.sender);
                                    if (fid != -1)

                                        addMessageReceive(netWork["yahoo"] + "_" + fid, message.msg);
                                }
                            });
                        }
                    }
                });
            }
        }, 2000);


        on(dom.byId("textSend"), "keypress", function (evt) {
            switch (evt.charCode) {
                case keys.ENTER:
                    var textSend = dom.byId("textSend");

                    SendMessageToServer(Myaccount.ID, textSend.value);

                    break;

            }
        });

        on(dom.byId("tabPanel"), "click", function () {
            var paneltab = registry.byId("tabPanel");

            var panelSelected = paneltab.selectedChildWidget;
            if (panelSelected != null) {
                var panelid = panelSelected.id;
                changeCurrentChat(SubID(panelid, "panel"));
            }
        });

        document.getElementById('file').addEventListener('change', loadimage, false);


        var textS = dom.byId("textSend");
        textS.value = "";
        var okdialog = dom.byId("okDialog");
        on(okdialog, "click", function () {
            addFriend();
        });
        var okDialogConnectYahoo = dom.byId("okDialogConnectYahoo");
        on(okDialogConnectYahoo, "click", function () {
            ConnectToYahoo();
        });


        var okDialogChangePassWord = dom.byId("okDialogChangePassWord");
        on(okDialogChangePassWord, "click", function () {
            changePassWord();
        });

        var sendbuttuon = dom.byId("SendButton");
        on(sendbuttuon, "click", function () {
            var textSend = dom.byId("textSend");



            SendMessageToServer(Myaccount.ID, textSend.value);

        });

        var okDialogChangeAvatar = dom.byId("okDialogChangeAvatar");
        on(okDialogChangeAvatar, "click", function () {
            if (ChangeAvatar) {
                SendImage(Myaccount.Username);
            }
            else
                alert("bạn chưa chọn hình nền khác!");
        });

        $.getJSON("http://localhost:40000/api/friend/" + idcurrent, function (data, textStatus) {

            console.log(textStatus);
            buildModel(data);
            $.each(data, function (i, item) {
                addDivAccount(netWork["webchat"] + "_" + i, item.FullName, item.Status);
            });
            AddMenu();




        });
        //beforeSend: function (XMLHttpRequest) {
        //    alert('Before Send');
        //    $('#loading').show();
        //},
        //complete: function (XMLHttpRequest, textStatus) {
        //    alert('Complete');
        //    $('#loading').hide();
        //}


    });
});

function SendImage(nickname) {

    var img = document.getElementById("currentavatar").src;
    $.ajax({

        url: "http://localhost:40000/api/account/" + nickname + "/avatar",


        contentType: 'image/jpeg',
        type: "POST",
        crossDomain: false,
        data: img,
        success: function (data) {
            document.getElementById('myavatar').src = "http://localhost:40000/api/account/" + Myaccount.ID + "/avatar";
            DialogChangeAvatar.onCancel();
            alert("Thay đổi avatar thành công");
            ChangeAvatar = false;

        },
        error: function (errMsg) {
            alert("Hình ảnh quá lớn không thể làm avatar.Nên chọn dưới 1.5mb");

        }
    });

}